<?php

namespace Kanin\Games;

use Kanin\Games\app\Distribute;
use Kanin\Games\lib\Tool;
use Kanin\Games\model\User;
use Swoole\Timer;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;

class gameServer {
	/**
	 * @var \swoole\Table
	 */
	public static $fdTable;

	/**
	 * @var \swoole\Table
	 */
	public static $userTable;

	/**
	 * @var Distribute
	 */
	public $distribute;

	public function onWorkerStart(Server $server, int $workerId) {
		require_once "vendor/autoload.php";
		// var_dump(get_included_files()); //此数组中的文件表示进程启动前就加载了，所以无法reload
		global $argv;
		if ($workerId >= $server->setting['worker_num']) {
			swoole_set_process_name("php {$argv[0]}: task_worker_{$workerId}");
		} else {
			swoole_set_process_name("php {$argv[0]}: worker_{$workerId}");
		}

		$this->distribute = new Distribute();
	}

	public function onOpen(Server $server, $req) {

	}

	public function onMessage(Server $server, Frame $frame) {
		$data = json_decode($frame->data, 1);
		$cmd = $data['cmd'];
		if (!empty($cmd)) {
			$cmd = '0x' . dechex($data['cmd']);
			if (!empty($data['token']) && !in_array($cmd, Distribute::NO_AUTH)) {
				$decode = User::decodeToken($data['token']);
				$uid = $decode['uid'] ?? 0;
				if (!$uid) {
					$server->push($frame->fd, json_encode(['cmd' => $cmd, ['code' => -999]]));
					$server->close($frame->fd);
				}
			}
			$msg = (new Distribute())->router($server, $frame);
		} else {
			$msg = "ok";
		}

		$server->push($frame->fd, $msg);
	}

	public function onClose(Server $server, $fd) {
		$info = self::$fdTable->get($fd);
		//移除废弃的记录
		self::$fdTable->del($fd);
		swoole_timer_clear($info['timer_id']);
		if (!empty($info['uid'])) {
			self::$userTable->del($info['uid']);
		}
	}

	public function onTask(Server $server, $task_id, $reactor_id, $data) {
		echo "New AsyncTask[id={$task_id}]" . PHP_EOL;
		//返回任务执行的结果
		$server->finish("{$data} -> OK");
	}

	public function onFinish(Server $server, $task_id, $data) {
		echo "AsyncTask[{$task_id}] Finish: {$data}" . PHP_EOL;
	}

	public function onWorkerExit(Server $server, int $worker_id)
	{
		Timer::clearAll();
		//swoole_event_del($this->process->pipe);
	}
}